import os

from PyQt5.QtWidgets import *

from encrypt_view import EncryptView
from file_view import FileView
import config
import encrypt
from login_dialog import LoginDialog
from user_manager import UserManager


class MainWin(QDialog):
    def __init__(self, user):
        super().__init__()
        self.user = user
        self.setWindowTitle(self.user.username)

        self.fileView = FileView()
        self.encryptView = EncryptView(user.username)

        self.fileView.encryptMenuClicked.connect(self.encrypt)
        self.encryptView.decryptMenuClicked.connect(self.decrypt)

        l = QHBoxLayout()
        l.addWidget(self.fileView)
        l.addWidget(self.encryptView)

        vl = QVBoxLayout()
        hl = QHBoxLayout()
        hl.addStretch()
        if user.is_admin():
            btn = QPushButton("用户管理")
            btn.clicked.connect(self.user_manager)
            hl.addWidget(btn)
        btn2 = QPushButton("修改密码")
        btn2.clicked.connect(self.change_password)
        hl.addWidget(btn2)

        vl.addLayout(hl)
        vl.addLayout(l)
        self.setLayout(vl)
        self.resize(900, 700)

    def change_password(self):
        loginDialog = LoginDialog()
        loginDialog.userEdit.setText(self.user.username)
        loginDialog.passwordEdit.setText(self.user.password)
        loginDialog.userEdit.setEnabled(False)
        if loginDialog.exec_() == QDialog.Accepted:
            self.user.set_password(loginDialog.password())

    def user_manager(self):
        self.u = UserManager(self.user)
        self.u.exec_()

    def encrypt(self):
        index = self.fileView.currentIndex()
        if index.isValid():
            fn = self.fileView.fileModel.filePath(index)
            if os.path.isfile(fn):
                encrypt.encrypt_file(self.user.key, fn, os.path.join(self.encryptView.RootDir, self.fileView.relpath(fn)))
                if not os.path.isdir(config.BackupDir):
                    os.makedirs(config.BackupDir)
                os.rename(fn, os.path.join(config.BackupDir, self.fileView.relpath(fn)))
                self.encryptView.fileModel.refresh(self.encryptView.rootIndex())
                self.fileView.fileModel.refresh(self.fileView.rootIndex())

    def decrypt(self):
        index = self.encryptView.currentIndex()
        if index.isValid():
            fn = self.encryptView.fileModel.filePath(index)
            if os.path.isfile(fn):
                encrypt.decrypt_file(self.user.key, fn, os.path.join(self.fileView.RootDir, self.encryptView.relpath(fn)))
                self.fileView.fileModel.refresh(self.fileView.rootIndex())

